import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout/index.vue'
import Dashboard from '@/views/Dashboard.vue'

Vue.use(VueRouter)

//路由规则
const routes = [
  {
    path: '/login',
    component: () => import('@/views/Login.vue'),
    name: 'Login',
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        component: Dashboard,
        name: 'Dashboard',
        meta: { title: '首页' }
      },
      {
        path: '/users',
        component: () => import('@/views/Users.vue'),
        name: 'Users',
        meta: { title: '用户管理' }
      },
      {
        path: '/roles',
        component: () => import('@/views/Roles.vue'),
        name: 'Roles',
        meta: { title: '角色管理' }
      },
      {
        path: '/permissions',
        component: () => import('@/views/Permissions.vue'),
        name: 'Permissions',
        meta: { title: '权限管理' }
      },
      {
        path: '/products',
        component: () => import('@/views/Products.vue'),
        name: 'Products',
        meta: { title: '产品管理' }
      },
      {
        path: '/orders',
        component: () => import('@/views/Orders.vue'),
        name: 'Orders',
        meta: { title: '订单管理' }
      },
      {
        path: '/settings',
        component: () => import('@/views/Settings.vue'),
        name: 'Settings',
        meta: { title: '系统设置' }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 获取token，这里可以根据实际情况从localStorage或vuex中获取
  const token = localStorage.getItem('token')
  
  // 如果前往登录页
  if (to.path === '/login') {
    // 如果已经登录，跳转到首页
    if (token) {
      next('/dashboard')
      return
    }
    // 未登录，允许访问登录页
    next()
    return
  }
  
  // 访问其他页面时，如果没有token，跳转到登录页
  if (!token) {
    next('/login')
    return
  }
  
  // 有token，正常访问
  next()
})

export default router